package com.ludum.game.map;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Scanner;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;


public class MapLoader {
	public static MapLoader loader = null;
	
	
		
	private Map map;
	
	private MapLoader(){
		map = null;		
	}
	
	static MapLoader getLoader(){
		if( loader == null ){
			loader = new MapLoader();
		}			
		
		return loader;
	}
	
	Map load(String file){
		InputStream src = Gdx.files.internal(file).read();
		Scanner scan = new Scanner(src);
		ArrayList<Block> l_block = new ArrayList<Block>();
		
		Vector2 spawn1 = new Vector2();
		Vector2 spawn2 = new Vector2();
		
				
		
		while (scan.hasNextLine()){
			Scanner tempscan = new Scanner(scan.nextLine());
			tempscan.useDelimiter(" ");
			
			String type = tempscan.next();
			
			if(type.equalsIgnoreCase("SPAWN")) {
				loadSpawns(tempscan.nextLine(), spawn1, spawn2);
			}
			else {	
				l_block.add(loadBlock(tempscan.nextLine(), type));
			}
		}
	
		scan.close();
		map = new Map(l_block, spawn1, spawn2);
	
		return map;
	}
	
	private void loadSpawns(String descr,
							Vector2 spawn1,
							Vector2 spawn2){
		Scanner scanSpawn = new Scanner(descr);

		spawn1.x = scanSpawn.nextFloat();
		spawn1.y = scanSpawn.nextFloat();
		spawn2.x = scanSpawn.nextFloat();
		spawn2.y = scanSpawn.nextFloat();	
	}
	
	private Block loadBlock(String descr, String type){
		Scanner scan = new Scanner(descr);
		
		float posx,posy, height, width;
		BlockType btype;
		
		btype = BlockType.valueOf(type);
		
		posx   = scan.nextFloat();
		posy   = scan.nextFloat();
		height = scan.nextFloat();
		width  = scan.nextFloat();
		
		
		
		Block block = new Block( new Vector2(posx, posy),
								 new Vector2(height, width),
								 btype);
		scan.close();
		
		return block; 
	}
}
